<?php
/*
 +-------------------------------------------------------------------+
 |                   builder.func.php                                 |
 |                                                                   |
 | Copyright ?                          www.gde.sclab.clarkson.edu   |
 | Author: Demetrios Dimatos            www.dimatos.net              |
 | Created: August 2006                 Last modified: Oct 15, 2006  |
 +-------------------------------------------------------------------+
 | These functions are used for the query builders                    |
 |  - /gde-1.0/templates/logged-in/builder.php                       |
 |  - /gde-1.0/templates/logged-in/builder-1.php                     |
 |  - /gde-1.0/templates/logged-in/builder-2.php                     |
 |  - /gde-1.0/templates/logged-in/builder-3.php                     |
 |  - /gde-1.0/includes/public/builder.ctl.php                       |
 +-------------------------------------------------------------------+
*/

 //Start the SESSION vars
  if (session_id() == "")
  { 
 	 session_start();
  }
 // Include configuration variables
 include_once('/var/www/gde-1.0/htdocs/config.php');
 // Include database connnection
 include_once(Config::base_path.Config::database_path."database.php");
  // Include templating for exceptions 
 include_once(Config::base_path.Config::adodb_path.'adodb-exceptions.inc.php');
  // Include html functions
 include_once(Config::base_path.Config::html_func_path."html.php");
 
 /**
  * maxListMultiple - returns the maximum number of options in a multiselect box
  * @param integer $num_records - number of records returned from a result set
  * best found by using adodb's RecordCount
  * @return integer - maximum for a multiselect box
  * @author Demetrios Dimatos
  */
 function maxListMultiple($num_records)
 {
   if($num_records > 5 )
   {
     return 5;
   }
   else
   {
     return $num_records;
   }
 }
 
 /**
  * buiildDatabaseQuery - queries for available databases, displays a select box, and begins building
  * the query off this information.
  * @author Demetrios Dimatos
  */
 function buildDatabaseQuery()  
 {
 	  echo '<br><br><br>';
		echo '<table width="700"><tr><td>';
    echo '<center>';
    echo '<div style="padding: 10px 5px 10px 5px; margin: 0px auto; width: 600px; border: 2px solid #ababab; background-color: #f1f1f1">';
    echo '<form action="'.'http://'.$_SERVER['HTTP_HOST'].'/gde-1.0/templates/logged-in/builder-1.php " method="post">';
    echo '<h3>Query Builder</h3>';
    echo '<table><tr><td align="left">';
    echo 'Build simple queries by choosing databases, tables, and fields.<br><br>';
    echo '</center>';
    // Use the adodb getMenu generation
    echo '<center>';
  //  $sql = 'SELECT databaseName FROM DatabaseInfo';
  $sql = 'show databases';
    $result = doQuery($sql,BACKEND);
    print $result->GetMenu('selected_database');
    echo '</center>';
    
    echo '<br><center>';
    echo '&nbsp;<input type="submit" name="next" value="Next"><br><br>';
    echo '</td></tr></table>';
    echo '</form>';
    echo '</div>';
    echo '</center>';
    echo '</td></tr></table>';
    echo '</body>';
    echo '</html>';
 }
 
 /**
  * buiilTableQuery - queries for tables based on selected database, prints a select box, and continues 
  * to build query from user selected information
  * @param string $selectedDatabase - database user chooses to view tables
  * @author Demetrios Dimatos
  */
 function buildTableQuery($selectedDatabase)
 {
 	  echo '<br><br><br>';
		echo '<table width="700"><tr><td>';
    echo '<center>';
    echo '<div style="padding: 10px 5px 10px 5px; margin: 0px auto; width: 600px; border: 2px solid #ababab; background-color: #f1f1f1">';
    echo '<form action="'.'http://'.$_SERVER['HTTP_HOST'].'/gde-1.0/templates/logged-in/builder-2.php " method="post">';
    echo '<h3>Query Builder</h3>';
    echo '<table><tr><td align="left">';
    echo 'Build simple queries by choosing databases, tables, tables, and fields.<br><br>';
    echo '</center>';
    // Use the adodb getMenu generation
    echo '<center>';
    $sql = 'SHOW tables FROM '.$selectedDatabase;
    $result = doQuery($sql,BACKEND);
    print $result->GetMenu('selected_table',null,false,true,maxListMultiple($result->RecordCount()));
    echo '</center>';
    
    echo '<br><center>';
    echo '&nbsp;<input type="submit" name="next" value="Next"><br><br>';
    echo '</td></tr></table>';
    echo '</form>';
    echo '</div>';
    echo '</center>';
    echo '</td></tr></table>';
    echo '</body>';
    echo '</html>';
 }
 
 /**
  * buildFieldQuery - queries for fields of selected database,selected tables, prints them in select box
  * and completes the query string built by the user.
  * @param string $selectedDatabase - database selected by user
  * @param string $selectedTable - table selected by user
  * @author Demetrios Dimatos
  */
 function buildFieldQuery($selectedDatabase,$selectedTable)
 {
    $onlyTwoColumns = 0; //Counter that maintains two columns per row
    //'/gde-1.0/templates/logged-in/editor.php 
    echo '<br><br><br>';
		echo '<table width="700"><tr><td>';
    echo '<center>';
    echo '<div style="padding: 10px 5px 10px 5px; margin: 0px auto; width: 600px; border: 2px solid #ababab; background-color: #f1f1f1">';
    echo '<form action="'.'http://'.$_SERVER['HTTP_HOST'].'/gde-1.0/templates/logged-in/builder-3.php " method="post">';
    echo '<h3>Query Builder</h3>';
    echo '<table><tr><td align="left">';
    echo 'Build simple queries by choosing databases, tables, tables, and fields.<br><br>';
    echo '</center>';
    
    // Set up the table
    echo '<table style="text-align: left; width: 100%;" border="1"  cellpadding="2" cellspacing="2">';
    echo '<tr>';
    
    // Traverse the 2xArray
    foreach($selectedTable as $table)
    {
      // Limit the slection boxes to two per row
      if($onlyTwoColumns == 2)
      {
        echo '</tr>';
        $onlyTwoColumns = 0;
      }
      
      echo '<td><center>';
      message2html($table,black);
      
      // Query each table for its columns based on number of tables chosen
      $sql = 'SHOW columns FROM '.$selectedDatabase.'.'.$table;
      $result = doQuery($sql,BACKEND);
      
      echo '<select name="selected_field_'.$table.'[]" multiple size="'.maxListMultiple($result->RecordCount()).'" >';
      while(!$result->EOF)
      {
        echo '<option value="'.$result->fields[0].'">'.$result->fields[0].'</option';
        $result->MoveNext();
      }
      //print $result->GetMenu('selected_field_',null,false,true,maxListMultiple($result->RecordCount()));
      echo '</select></center><br></td>';
      $onlyTwoColumns++;
    }
    
    echo '</tr></table>';
    echo '<br><center>';
    echo '&nbsp;<input type="submit" name="next" value="Next"><br><br>';
    echo '</td></tr></table>';
    echo '</form>';
    echo '</div>';
    echo '</center>';
    echo '</td></tr></table>';
    echo '</body>';
    echo '</html>';
 }
 
 /**
  * buildQueryString - parses $_session and $_post globals to build a query string based on the user
  * selected fields 
  * @return string - query string
  * @author Demetrios Dimatos
  */
 function buildQueryString()
 {
  $bool_where_once = true;
  $selected_query_string = 'SELECT ';
  
  foreach($_SESSION['selected_table'] as $table)
  {
    //  $_SESSION['selected_field_'.$table] = $_POST['selected_field_'.$table];
      if(isset($_SESSION['selected_field_'.$table]))
      {
        foreach ($_SESSION['selected_field_'.$table] as $field)
        {
          $selected_query_string .= $table.'.`'.$field.'`';
          $selected_query_string .= ' , ';
        }
      }
  }
  
  // Get rid of the lingering comma
  if($_SESSION['selected_field_'.$table] )
  {
    $selected_query_string =  substr($selected_query_string,0,strlen($selected_query_string) - 2);
  }
  
  // If not fields have been selected use "*" regex
  if(!$_SESSION['selected_field_'.$table] )
  {
    $selected_query_string .= ' * ';
  }
  
  $selected_query_string .= ' FROM ';
  
  foreach($_SESSION['selected_table'] as $table)
  {
    $selected_query_string .= $_SESSION['selected_database'];
    $selected_query_string .= '.'.$table. ' ';
    $selected_query_string .= ' , ';
  }
  $selected_query_string =  substr($selected_query_string,0,strlen($selected_query_string) - 2);
 // $selected_query_string .= ';';
  
 foreach ($_SESSION['selected_table'] as $table)
 {
   if($bool_where_once)
   {
      $selected_query_string .= ' WHERE ';
      $bool_where_once = false;
   }
   else 
   {
     $selected_query_string .= ' AND ';
   }
   if(isset($_SESSION['selected_table_join_'.$table]))
   {
      $selected_query_string .= $table;
      $selected_query_string .= '.';
      $selected_query_string .= $_SESSION['selected_table_pk_'.$table];
      $selected_query_string .= ' = ';
      $selected_query_string .= $_SESSION['selected_table_join_'.$table];
      $selected_query_string .= '.';
      $selected_query_string .= $_SESSION['selected_table_pk_'.$table];
   }
   elseif(isset($_SESSION['selected_table_where_'.$table]))
   {
      $selected_query_string .= $table;
      $selected_query_string .= '.';
      $selected_query_string .= $_SESSION['selected_table_where_'.$table];
      $selected_query_string .= ' = "';
      $selected_query_string .= $_SESSION['selected_table_text_'.$table];
      $selected_query_string .= '"';
   }
   else 
   {
     $selected_query_string =  substr($selected_query_string,0,strlen($selected_query_string) - 7);
   }
 }
  //$selected_query_string =  substr($selected_query_string,0,strlen($selected_query_string) - 2);
  return $selected_query_string;
 }
 
 /**
  * queryEditor - displays the query editor with the user built query string with options
  * @param string $query_string - query string to be displayed by default in the qeury editor.
  * @author Demetrios Dimatos
  */
 function queryEditor($query_string)
 {
    echo '<br><br><br>';
    echo '<table width="700"><tr><td>';
    echo '<center>';
    echo '<div style="padding: 10px 5px 10px 5px; margin: 0px auto; width: 600px; border: 2px solid #ababab; background-color: #f1f1f1">';
    echo '<form action="'.'http://'.$_SERVER['HTTP_HOST'].'/gde-1.0/templates/logged-in/query-results.php " method="post">';
    echo '<h3>Query Editor</h3>';
    echo '<table><tr><td align="left">';
    echo 'Enter a query directly that you can save and/or run now or edit an existing query.<br><br>';
    echo '</td></tr></table>';
    echo '<textarea name="editor" cols="60" rows="10">'.$query_string.'</textarea>';
    echo '<br><br>';
    echo '<input type="submit" name="load" value="Load Query" disabled >&nbsp';
    echo '<input type="submit" name="save" value="Save Query" disabled >&nbsp';
    echo '<input type="submit" name="run" value="Run Query">&nbsp';
    echo '<input type="submit" name="save-run" value="Save &amp; Run Query" disabled>';

    echo '</form>';
    echo '</div>';
    echo '</center>';
    echo '</td></tr></table>';
    echo '</body>';
    echo '</html>';
 }
 
 /**
  * get_database_pk() - Searches for all databases managed by GDE excluding system databses
  * locating all primary key and puting them in a talbe with the database name appended to
  * "`BDAP_'.$result->fields[0].'_tables_pk`"
  * 
  * @author Demetrios Dimatos
  */
 function get_database_pk()
 {
   $sql = "SHOW databases";
   $result = doQuery($sql,BACKEND);
   
   while(!$result->EOF)   // Get each database
   { 
     // Var to create a non pk talbe only once per database traversal
     $bool_non_pk_table_once = true;
     
     if($result->fields[0] != "information_schema" && $result->fields[0] != "mysql" && $result->fields[0] != "BDAP")
     {
       // create the database to store all the primary keys
       $sql_drop_table = 'DROP TABLE IF EXISTS `BDAP_'.$result->fields[0].'_tables_pk`'; 
       $sql_create_table = 'CREATE TABLE IF NOT EXISTS `BDAP_'.$result->fields[0].'_tables_pk` (
       `'.$result->fields[0].'_tables_pk_id` int unsigned NOT NULL auto_increment,
       `table_pk_name` varchar(255) NOT NULL,
       `primary_key` varchar(255) NOT NULL,
       PRIMARY KEY  (`'.$result->fields[0].'_tables_pk_id`)) 
       ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=201';
        
       // Drop the talbe if exists 
       doQuery($sql_drop_table,BACKEND);
       // Create teh pk table
       doQuery($sql_create_table,BACKEND);
       
       //echo "<br>[ Database =>".$result->fields[0]." ]";
       
       // Select all tables from the database
       $sql_tables = 'SHOW tables from '.$result->fields[0];
       $result_tables = doQuery($sql_tables,BACKEND);
       
       // Get each table and check if it has a pk
       while(!$result_tables->EOF)
       {
          //echo "<br>..table ==>[ ".$result_tables->fields[0]." ]"; 
                  
          $db = db_pconnect(Config::db_type,Config::db_host,Config::db_username,Config::db_password,$result->fields[0],Config::errors);
          $result_pk = $db->MetaPrimaryKeys($result_tables->fields[0]); // Get eeach PK from tables
          // print_r($result_pk);
         
         if($result_pk)
         {
           foreach ($result_pk as $primary_key)
           {
              // If its an array traverse it and insert into the table with all pk's             
              if(is_array($primary_key))
              {
                foreach ($primary_key as $key)
                {
                  //echo "<br>....key1 ===>[ ".$key." ]";
                  
                  $sql_insert_pk_values = 'INSERT INTO `BDAP_'.$result->fields[0].'_tables_pk` (`table_pk_name` , `primary_key` )VALUES (\''.$result_tables->fields[0].'\', \''.$key.'\')';
                  doQuery($sql_insert_pk_values,BACKEND);
                }
              }
              else  // Not an array
              {
                //echo "<br>....key ===>[ ".$primary_key." ]";
                
                 $sql_insert_pk_value = 'INSERT INTO `BDAP_'.$result->fields[0].'_tables_pk` (`table_pk_name` , `primary_key` )VALUES (\''.$result_tables->fields[0].'\', \''.$primary_key.'\')';
                 doQuery($sql_insert_pk_value,BACKEND);
              }
            }
         }
         else  // There is not primary key for this talbe in this database
         {
            if($bool_non_pk_table_once)
            {
              // create the database to store all the tables with no pk's for use with a where clause
              $sql_drop_table = 'DROP TABLE IF EXISTS `BDAP_'.$result->fields[0].'_tables_non_pk`';
              $sql_create_table = 'CREATE TABLE IF NOT EXISTS `BDAP_'.$result->fields[0].'_tables_non_pk` (
              `'.$result->fields[0].'_tables_non_pk_id` int unsigned NOT NULL auto_increment,
              `table_non_pk_name` varchar(255) NOT NULL,
              PRIMARY KEY  (`'.$result->fields[0].'_tables_non_pk_id`)) 
              ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=201';

              // Drop the talbe if exists
              doQuery($sql_drop_table,BACKEND);
              // Create the non pk table
              doQuery($sql_create_table,BACKEND);
              
              $bool_non_pk_table_once = false;
            }
            
            // Insert into the non pk table the tables who don't have a pk.
            // Use this table to do a "where" clause for those tables w/no pk/fk relationships
            $sql_insert_non_pk_values = 'INSERT INTO `BDAP_'.$result->fields[0].'_tables_non_pk` ( `'.$result->fields[0].'_tables_non_pk_id` , `table_non_pk_name` ) VALUES (NULL , \''.$result_tables->fields[0].'\')';
            doQuery($sql_insert_non_pk_values,BACKEND);
            // echo "<br>....key ===>[ NULL ]"; 
         }
         $result_tables->MoveNext(); 
       }
     }
     $result->MoveNext();
   }
 }
 
 /**
  * get_database_fk() - Reviews all databases managed by GDE, taking each table from each database exlcluding
  * system databases and finding all foreign keys in each table. Foreign keys are inserted in a table 
  * concatenated with the database name "BDAP_'.$result->fields[0].'_tables_fk" and makes a relationship to 
  * its primary key table partner, see get_database_pk()
  * 
  * @author Demetrios Dimatos
  */
 function get_database_fk()
 {
   $sql = "SHOW databases";
   $result = doQuery($sql,BACKEND);
   
   while(!$result->EOF)   // Get each database
   { 
     if($result->fields[0] != "information_schema" && $result->fields[0] != "mysql" && $result->fields[0] != "BDAP")
     {
        // create the database to store all the primary keys
         $sql_drop_table = 'DROP TABLE IF EXISTS `BDAP_'.$result->fields[0].'_tables_fk`'; 
         $sql_create_table = 'CREATE TABLE IF NOT EXISTS `BDAP_'.$result->fields[0].'_tables_fk` (
          `'.$result->fields[0].'_tables_fk_id` int unsigned NOT NULL auto_increment,
          `table_fk_name` varchar(255) NOT NULL,
          `'.$result->fields[0].'_tables_pk_id` int unsigned NOT NULL,
          PRIMARY KEY  (`'.$result->fields[0].'_tables_fk_id`),
          KEY `idx_'.$result->fields[0].'_tables_pk_id` (`'.$result->fields[0].'_tables_pk_id`)
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=201';
        
        // Drop the talbe if exists 
        doQuery($sql_drop_table,BACKEND);
        // Create teh pk table
        doQuery($sql_create_table,BACKEND);
       
       //echo "<br>[ Database =>".$result->fields[0]." ]";
       
       // Select all tables from the database
       $sql_tables = 'SHOW tables from '.$result->fields[0];
       $result_tables = doQuery($sql_tables,BACKEND);
       
       // Get each table and check if it has a Foreign Key
       while(!$result_tables->EOF) 
       {
         // echo "<br>..table ==>[ ".$result_tables->fields[0]." ]"; 
                  
          $db = db_pconnect(Config::db_type,Config::db_host,Config::db_username,Config::db_password,$result->fields[0],Config::errors);
          $result_fk = $db->MetaForeignKeys($result_tables->fields[0]); // Get eeach PK from tables
          // print_r($result_pk);
         
         if($result_fk)
         {
           foreach ($result_fk as $foreign_key)
           {  
              // An array of foreign keys
              if(is_array($foreign_key))
              {
                foreach ($foreign_key as $key)
                {
                  //echo "<br>....key1 ===>[ ".strtok($key,"=")." ]";
                  
                   // Find the primary key id that matches the foreign key we have and insert the pk id into  `BDAP_'.$result->fields[0].'_tables_fk`
                   $sql_find_pk = 'select '.$result->fields[0].'_tables_pk_id from BDAP_'.$result->fields[0].'_tables_pk where primary_key="'.strtok($key,"=").'"';
                   $find_pk = doQuery($sql_find_pk,BACKEND);
                   if($find_pk->fields[0] != 0)
                   {
                     $sql_insert_pk_value = 'INSERT INTO `BDAP_'.$result->fields[0].'_tables_fk` (`table_fk_name` , `sakila_tables_pk_id` ) VALUES (\''.$result_tables->fields[0].'\', \''.$find_pk->fields[0].'\')';
                     doQuery($sql_insert_pk_value,BACKEND);
                   }
                }
              }
              else
              {
                //echo "<br>....key ===>[ ".strtok($primary_key,"=")." ]";
                
                 // Find the primary key id that matches the foreign key we have and insert the pk id into  `BDAP_'.$result->fields[0].'_tables_fk`
                 $sql_find_pk = 'select '.$result->fields[0].'_tables_pk_id from BDAP_'.$result->fields[0].'_tables_pk where primary_key="'.strtok($primary_key,"=").'"';
                 $find_pk = doQuery($sql_find_pk,BACKEND);
                 $sql_insert_fk_value = 'INSERT INTO `BDAP_'.$result->fields[0].'_tables_fk` (`table_fk_name` , `sakila_tables_pk_id` ) VALUES (\''.$result_tables->fields[0].'\', \''.$find_pk->fields[0].'\')';
                 doQuery($sql_insert_fk_value,BACKEND);
              }
            }
         }
         else  // Else no foreign key was found
         {
           // echo "<br>....key ===>[ NULL ]"; 
         }
         $result_tables->MoveNext(); 
       }
     }
     $result->MoveNext();
   }
 }
 
 /**
  * For each selected table in the query builder, "buildInnerJoins" will query the pk and fk tables
  * maintained by GDE to build an html talbe that will present all primary and foreign key relationships
  * as well as where clauses to be passed to the query editor.
  *
  * @param string $selectedDatabase - $_SESSION['selected_database'] variable containing users selected 
  * databases created by query builder
  * @param string $selectedTables - $_SESSION['selected_tables'] array containing users selected tables 
  * created by the query builder
  * @author Demetrios Dimatos
  */
 function buildInnerJoins($selectedDatabase, $selectedTables)
 {
   // For each selected $selectedTables name find it in BDAP_$selecteDatabase_tables_pk and obtain
   // $selecteDatabase_tables_pk_id and join to BDAP_$selecteDatabase_tables_fk to find all 
   // $selecteDatabase_tables_pk_id = $selecteDatabase_tables_pk_id and return all table_fk_name
   // At this point we know enough to build a grid to display all this info.
   
   // select table_fk_name from BDAP.BDAP_sakila_tables_fk , BDAP.BDAP_sakila_tables_pk 
   // where BDAP_sakila_tables_pk.table_pk_name = 'customer' and 
   // BDAP_sakila_tables_pk.sakila_tables_pk_id = BDAP_sakila_tables_fk.sakila_tables_pk_id;

    echo '<br><br><br>';
		echo '<table width="700"><tr><td>';
    echo '<center>';
    echo '<div style="padding: 10px 5px 10px 5px; margin: 0px auto; width: 700px; border: 2px solid #ababab; background-color: #f1f1f1">';
    echo '<form action="'.'http://'.$_SERVER['HTTP_HOST'].'/gde-1.0/templates/logged-in/editor.php " method="post">';
    echo '<h3>Query Builder</h3>';
    echo '<table><tr><td align="left">';
    echo 'Build simple queries by choosing databases, tables, tables, and fields.<br><br>';
    echo '</center>';
    
     // Set up the table
     echo '<table style="text-align: left; width: 675px;" border="1"  cellpadding="2" cellspacing="2">';
     echo '<tr><td><center><b>Table constraint</b></center></td><td><center><b>Relationship</b></center></td.<td><center><b>Referential constraint</b></center></td></tr>';
     
     // Traverse the chosen tables from the query builder
     foreach($_SESSION['selected_table'] as $table)
     {
        // For each table query locate its pk/fk relationships described above
        $sql_find_pk_names = 'select table_fk_name, primary_key from BDAP_'.$selectedDatabase.'_tables_fk , BDAP.BDAP_'.$selectedDatabase.'_tables_pk
        where BDAP_'.$selectedDatabase.'_tables_pk.table_pk_name = \''.$table.'\' and 
        BDAP_'.$selectedDatabase.'_tables_pk.'.$selectedDatabase.'_tables_pk_id = BDAP_'.$selectedDatabase.'_tables_fk.'.$selectedDatabase.'_tables_pk_id';
        $find_pk_name = doQuery($sql_find_pk_names,BACKEND);

        // Result must have at least one pk and the fk name must be a selected table
        if($find_pk_name->RecordCount() != 0 && in_array($find_pk_name->fields[0],$_SESSION['selected_table']))
        { 
          echo '<tr><td> WHERE &nbsp '.$table.'<b> &nbsp . &nbsp </b>'.$find_pk_name->fields[1].'</td>';
          echo '<td><center> = </center></td><td>';
          echo '&nbsp&nbsp<select name ="selected_table_join_'.$table.'">';
          
          // Put all the pk table names into a select box
          while(!$find_pk_name->EOF)
          {
            // Insert the table and pk into a session variable for later use by query builder
            $_SESSION['selected_table_pk_'.$table] = $find_pk_name->fields[1];
            echo '<option value="'.$find_pk_name->fields[0].'">'.$find_pk_name->fields[0].'</option>';
            $find_pk_name->MoveNext();
          }
          echo '</select> &nbsp<b> . </b> &nbsp '.$_SESSION['selected_table_pk_'.$table].'</td></tr>';
        }
        else // result set must be from a view or table w/no pk/fk relationship
        {   
           $db = db_connect(Config::db_type,Config::db_host, Config::db_username,Config::db_password,Config::db_database,Config::errors);
           $column_names= $db->MetaColumnNames($selectedDatabase.'.'.$table);
           //print_r($column_names);
           echo '<tr><td> WHERE &nbsp '.$table.'<b> &nbsp . </b>'.'</td>';
           echo '<td>&nbsp&nbsp <select name ="selected_table_where_'.$table.'">';
           foreach ($column_names as $column)
           {
             echo '<option value="'.$column.'">'.$column.'</option';
             //$column_names->MoveNext();
           }
           echo '</select> &nbsp&nbsp = </td>';
           echo '<td>&nbsp&nbsp<input type = \'text\' value = " -- Enter a value --" name = "selected_table_text_'.$table.'"></td></tr>';
        }
     }
    
    echo '</tr></table>';
    echo '<br><center>';
    echo '&nbsp;<input type="submit" name="next" value="Next"><br><br>';
    echo '</td></tr></table>';
    echo '</form>';
    echo '</div>';
    echo '</center>';
    echo '</td></tr></table>';
    echo '</body>';
    echo '</html>';
 }
 ?>